﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using System.Windows.Forms;
using System.Timers;
using System.Threading.Tasks;

namespace MediaPlayer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private List<VideoListClass> videoListClass = new List<VideoListClass>();
        private string currentlySelectedVideo;
        private bool IsMuted;

        public MainWindow()
        {
            InitializeComponent();
        }

        
        private void MediaEl_MediaOpened(object sender, RoutedEventArgs e)
        {
            TimeSlider.Maximum = MediaEl.NaturalDuration.TimeSpan.TotalMilliseconds;
            timer();
        }
        private void timer()
        {
            System.Timers.Timer ElapsedVideoTimer = new System.Timers.Timer(100);
            ElapsedVideoTimer.Elapsed += delegate(object sender, ElapsedEventArgs e)
            {
                Dispatcher.BeginInvoke(new Action(() =>
                    {
                        //- Display elapsed time
                        if (VideoTimer.Tag.ToString() == "Elapsed")
                            VideoTimer.Content = MediaEl.Position.Hours.ToString("00")
                                + ":" + MediaEl.Position.Minutes.ToString("00") + ":" + MediaEl.Position.Seconds.ToString("00");
                        //- Display remaining time
                        else
                        {
                            TimeSpan a = MediaEl.NaturalDuration.TimeSpan - MediaEl.Position;
                            VideoTimer.Content = "-" + a.ToString();
                        }
                        TimeSlider.Value = MediaEl.Position.TotalMilliseconds;
                        if (MediaEl.Position == MediaEl.NaturalDuration /*&& flag_repeate*/ == true)
                            MediaEl.Position = new TimeSpan(0, 0, 0);
                    }));
            };
            ElapsedVideoTimer.Start();
        }


        private void PlayBtn_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            PlayPause();
        }
        private void StopBtn_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            StopPlay();
        }
        private void OpenBtn_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            OpenFile(); 
            MediaEl.Play();
        }

        // TimeSlider events
        private void TimeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {

            if (TimeSlider.IsMouseOver && TimeSlider.IsMouseCaptureWithin)
            {
                TimeSpan ts = new TimeSpan(0, 0, 0, 0, (int)TimeSlider.Value);

                MediaEl.Position = ts;

            }
        }
        private void TimeSlider_GiveFeedback(object sender, System.Windows.GiveFeedbackEventArgs e)
        {
            TimeSpan ts = new TimeSpan(0, 0, 0, 0, (int)TimeSlider.Value);
            MediaEl.Position = ts;
        }


        private void ScreenBtn_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            string Directory_name = "c:";//придумать как будет задаваться папка куда сохр скрины
            try
            {
                MediaEl.SaveScreenshot(Directory_name);
            }
            catch { System.Windows.Forms.MessageBox.Show("Нічого фотографувати"); }
        }

        private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized)
            {
                PanelwithTimeSlider.Visibility = Visibility.Hidden;
                PanelwithBtn.Visibility = Visibility.Hidden;
                MediaEl.Margin = new Thickness(0, 0, 0, 0);
                this.WindowStyle = WindowStyle.None;
                this.Topmost = true;
                this.WindowState = WindowState.Maximized;
                MediaEl.Height = MainForm.Height;
            }
            else
            {
                PanelwithTimeSlider.Visibility = Visibility.Visible;
                PanelwithBtn.Visibility = Visibility.Visible;
                MediaEl.Margin = new Thickness(0, 10, 0, 63);
            }
        }

        private void Window_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {

            if (this.WindowState == WindowState.Maximized)
            {
                if (rectangle1.IsPointInRect(e.GetPosition(this)))
                {
                    PanelwithTimeSlider.Visibility = Visibility.Hidden;
                    PanelwithBtn.Visibility = Visibility.Hidden;
                    MediaEl.Margin = new Thickness(0, 0, 0, 0);
                    this.WindowStyle = WindowStyle.None;
                    this.Topmost = true;
                    MainMenu.Visibility = Visibility.Hidden;
                }
                else
                {
                    this.WindowStyle = WindowStyle.SingleBorderWindow;
                    PanelwithTimeSlider.Visibility = Visibility.Visible;
                    PanelwithBtn.Visibility = Visibility.Visible;
                    MediaEl.Margin = new Thickness(0, 0, 0, 79);
                    MainMenu.Visibility = Visibility.Visible;
                }
            }

        }

        private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.SystemKey == Key.LeftAlt)
                if (this.WindowStyle != WindowStyle.None)
                {
                    this.WindowStyle = WindowStyle.None;
                    this.WindowState = WindowState.Maximized;
                    this.Topmost = true;

                }
                else
                {
                    this.WindowStyle = WindowStyle = WindowStyle.SingleBorderWindow;
                    this.WindowState = WindowState.Normal;
                    this.Topmost = false;
                }
            if (e.SystemKey == Key.RightAlt)
            {
                string Directory_name = "c:";//придумать как будет задаваться папка куда сохр скрины
                try
                {
                    MediaEl.SaveScreenshot(Directory_name);
                }
                catch { System.Windows.Forms.MessageBox.Show("Нічого фотографувати"); }
            }

        }

        private void rectangle2_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            VideoList vlw = new VideoList(videoListClass, ref currentlySelectedVideo, MediaEl);
            vlw.Show();
        }

     

        
        //-Методы для событий
        private void OpenFile()
        {
            System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();

            ofd.Filter = "Audio-Video Files|*.mp3;*.wma;*.avi;*.mpeg;*.wmv|" +
                         "All Files|*.*";

            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                VideoListClass vl = new VideoListClass(ofd.FileName);
                videoListClass.Add(vl);
                currentlySelectedVideo = vl.FileUrl;
                MediaEl.Source = new Uri(currentlySelectedVideo);
                PlayBtn.IsEnabled = true;
            }
        }
        private void PlayPause()
        {
            ImageBrush ib = new ImageBrush();
           
            if (MediaEl.Tag.ToString() == "Stoped")
            {
                ib.ImageSource = new BitmapImage(new Uri("pack://application:,,,/image/PauseHot.png"));
                MediaEl.Play();
                PlayBtn.Fill = ib;
                if (MediaEl.HasVideo == false)
                    VideoTimer.Visibility = Visibility.Visible;
                else
                    VideoTimer.Visibility = Visibility.Visible;
                MediaEl.Tag = "Played";
            }
            else
            {
                MediaEl.Pause();
                ib.ImageSource = new BitmapImage(new Uri("pack://application:,,,/image/Play1Hot.png"));
                PlayBtn.Fill = ib;
                MediaEl.Tag = "Stoped";
            }
        }
        private void StopPlay()
        {
            MediaEl.Stop();

            PlayBtn.Fill = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/image/Play1Hot.png")));
            MediaEl.Tag = "Stoped";
        }
        
        //-Set video timer visualization mode
        private void VideoTimer_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            VideoTimer.Tag = (VideoTimer.Tag.ToString() == "Elapsed") ? "Remain" : "Elapsed";
        }

        // Sound level
        private void VolumSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            MediaEl.Volume = VolumSlider.Value / 10;
            if (IsMuted == true)
                VolumePict.Fill = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/image/Sounds.png")));
            IsMuted = false;

            if (VolumSlider.Value == 0)
            {
                VolumePict.Fill = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/image/Off.png")));
                IsMuted = true;
            }

        }
        
        // Sound level by wheel of mouse
        private void MainForm_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (e.Delta > 0)
                VolumSlider.Value += 1;
            else
                VolumSlider.Value -= 1;

        }
        
        // Speakers balance
        private void BalanceSlide_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            MediaEl.Balance = (BalanceSlide.Value / 5) - 1;
        }
        
        // Mute sounds
        private void VolumePict_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ImageBrush Pict = new ImageBrush();

            if (IsMuted == false)
            {
                Pict.ImageSource = new BitmapImage(new Uri("pack://application:,,,/image/Off.png"));
                VolumePict.Fill = Pict;
                VolumePict.Tag = (int)VolumSlider.Value;
                VolumSlider.Value = 0;

                IsMuted = true;
            }
            else
            {
                Pict.ImageSource = new BitmapImage(new Uri("pack://application:,,,/image/Sounds.png"));
                VolumePict.Fill = Pict;
                VolumSlider.Value = Convert.ToDouble(VolumePict.Tag);

                IsMuted = false;
            }


        }
        
        // Shortkeys
        private void MainForm_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.I:
                    AboutWin F = new AboutWin();
                    F.ShowDialog();
                    break;
                case Key.O:
                    OpenFile(); break;
                case Key.Space:
                    PlayPause(); break;
                case Key.C:
                    StopPlay(); break;
                case Key.Escape:
                    MainForm.Close(); break;
                case Key.P:
                    VideoList vlw = new VideoList(videoListClass, ref currentlySelectedVideo, MediaEl);
                    vlw.Show();
                    break;
            }
        }
        #region Обработка Кнопок меню

        private void MenuItem_OpenFile(object sender, RoutedEventArgs e)
        {
            OpenFile();
        }
        private void MenuItem_Play(object sender, RoutedEventArgs e)
        {
            PlayPause();
        }

        // Stop playing
        private void MenuItem_StopPlaying(object sender, RoutedEventArgs e)
        {

        }

        // Close
        private void MenuItem_CloseMainWin(object sender, RoutedEventArgs e)
        {
            MainForm.Close();
        }

        // About
        private void AboutMenu_Click(object sender, RoutedEventArgs e)
        {
            AboutWin F = new AboutWin();
            F.ShowDialog();
        }

        private void IncrSpeedMenu_Click(object sender, RoutedEventArgs e)
        {
            MediaEl.SpeedRatio = MediaEl.SpeedRatio * 2;
        }
        private void DecrSpeedMenu_Click(object sender, RoutedEventArgs e)
        {
            MediaEl.SpeedRatio = MediaEl.SpeedRatio / 2;
        }


        // Open Playlist
        private void MenuItem_OpenPlaylist(object sender, RoutedEventArgs e)
        {
            VideoList vlw = new VideoList(videoListClass, ref currentlySelectedVideo, MediaEl);
            vlw.Show();
            vlw.Topmost = true;

        }

        #endregion;

    }

}
